package com.kaliterre.kalidroid.broadcastreceiver;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.kaliterre.kalidroid.dal.BatteryLogDAL;
import com.kaliterre.kalidroid.entity.BatteryLog;

/**
 * @author FIL A2 - Alyssa Boucher, Maxime Bureau, Yohan Mercier, Nicolas Mortier, Zakaria Oualkadi.
 *
 *	Custom BroadcastReceiver to catch power call events. 
 *	
 */
public class PhoneCallReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		
		Log.e("", "************************ "+ intent.getAction() + " ************************");
		SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
		
		Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
		
		int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
		int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
		int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
		int temp = batteryIntent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
		int voltage = batteryIntent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
		String batteryLevel = String.valueOf(level/scale*100);
		
		int state = intent.getIntExtra(TelephonyManager.EXTRA_STATE,-1);
		String callEvent = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
		
	    if(TelephonyManager.CALL_STATE_RINGING == state) {
	    	callEvent = "RINGING";
	    }
	    if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
	    	callEvent = "OFFHOOK";
	    }
	    if(TelephonyManager.CALL_STATE_IDLE == state) {
	    	callEvent = "IDLE";
	    }
		Log.i("LEVEL", level + "**********");	
		// Create the log.
		BatteryLog log = new BatteryLog(formatDate.format(new Date()), intent.getAction()  + " : " + callEvent, String.valueOf(level),String.valueOf(voltage), String.valueOf(temp), String.valueOf(status));
		// Create object to access to the DB.
		BatteryLogDAL battryLogDal = new BatteryLogDAL(context);

		// Open the access to the DB.
		battryLogDal.open();
		// Insert the battery log.
		battryLogDal.insertBatteryLog(log);

		// Close the access to the DB.
		battryLogDal.close();
		
	}
	
	public IntentFilter getIntentFilterActions()
	{
		IntentFilter intentFilterPhoneCall = new IntentFilter();
		intentFilterPhoneCall.addAction(Intent.ACTION_CALL);
		intentFilterPhoneCall.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
		intentFilterPhoneCall.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);

		return intentFilterPhoneCall;
	}
}
